package designPatterns.com.course_design.scrapy;

import designPatterns.com.course_design.scrapy.spider.RequestHandler;

import java.util.ArrayList;
import java.util.List;

public class RequestHandlerRegistry {
    private List<RequestHandler> handlers = new ArrayList<>();

    public void addRequestHandler(RequestHandler handler){
        this.handlers.add(handler);
    }

    public void addRequestHandler(int index,RequestHandler handler){
        if(index > this.handlers.size() || index< 0)
            throw new ArrayIndexOutOfBoundsException("插入元素不在列表范围内");
        this.handlers.add(index,handler);
    }

    /**
     * 构建责任链，职责链模式
     */
    public void buildRequestHandlerChain(){
        assert this.handlers.size()>1;
        for (int i = 0; i < this.handlers.size()-1; i++) {
            this.handlers.get(i).setNextHandler(this.handlers.get(i+1));
        }
    }
}
